<?php
/**
 * 《合同明细》实现类
 *
 * @author 孙晓晔
 * @version $Id: Country.class.php 832 2010-01-06 09:17:14Z xuy $
 */
require_once(dirname(__FILE__) . '/FinanceUtil.class.php');

class ContractItem extends FinanceUtil {
	public $tbl = Constant::tbl_cw_contract_item;
	
	public $percent = array(
		'-' => '请选择',
		'0.8' => '80%',
		'0.7' => '70%',
		'0.6' => '60%',
		'0.5' => '50%',
		'0.4' => '40%',
		'0.3' => '30%',
		'0.2' => '20%',
		'0.1' => '10%',
		'0.05' => '5%',
	);
		
	public $status = array(
		'-' => '请选择',
		'1' => '新建合同',
		'2' => '等待审核',
		'3' => '正在执行',
		'4' => '已经完成',
	
		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'invoice' => '开票日期',
		'date' => '到帐日期',
	
		'customer' => '客户',
		'emp' => '业务员',
		'engineer' => '工程师',		
	
		'type' => '类型',
		'currency' => '币种',
		'amount' => '金额',		
		'status' => '状态',

		'1' => '创建时间',
		'2' => '更新时间',
	);
	
	public $groupby = array(
		'-' => '请选择',
		'customer' => '客户',		
		'currency' => '币种',
		'type' => '类型',
		'emp' => '业务员',
		'status' => '状态',
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);
		
		$controller->assign_by_ref('percent_option', $this->percent);
	}
	
	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);

		// $controller->assign('t1', strtotime('-1 year'));
		
		$controller->display($request, 'finance/contract/item/find');
		return true;
	}
	
	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}
		
		if ($px == 'type') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $this->type[$row['type']];
		}
		
		if ($px == 'invoice') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['invoice'];
		}
		
		if ($px == 'date') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['date'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$contract_s = $request['contract_s'];
		$transaction_s = $request['transaction_s'];		
		
		$engineer_s = $this->_input($request['engineer_s']);
		
		$name_s = $request['name_s'];		
		$type_s = $request['type_s'];

		$my = $this->_my();

		if (empty($my)) {
			$where = " WHERE 1=1";
		} else {
			$where = " WHERE " . $my;
		}

		if (!empty($contract_s)) {
			$where .= $this->_x_s("`contract`", $contract_s);
		}
		
		if (!empty($transaction_s)) {
			$where .= $this->_x_s("transaction", $transaction_s);
		}
		
		if (!empty($engineer_s)) {
			$where .= " AND engineer = '" . $engineer_s . "'";
		}
		
		if (!empty($name_s)) {
			$where .= " AND name LIKE '%" . $name_s . "%'";
		}
		
		$where .= $this->_where_x("type", $request['type_s']);
		
		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}
	
	function _my() {
		if ($this->_is_admin()) {
			return '';
		}

		$emp = $_SESSION['id'];
		
		$p = array('1'=>'161', '2'=>'162', '3'=>'173');
		
		$a = $this->_audit_office($p);
		if (count($a) > 0) {
			$office = implode(",", $a);
			
			return sprintf(" visible = 1 AND (office in (%s) OR emp = '%s' OR oper = '%s')", $office, $emp, $emp);
		}		

		return sprintf(" visible = 1 AND (emp = '%s' OR oper = '%s')", $emp, $emp);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();
				
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {
			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'finance/contract/item/list');
		return true;
	}
		
	function xls($controller, $request) {
		$this->pretreat($controller);
		
		$this->findPara($controller, $request);

		$request['tpl'] = "xls";

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {			
			$row = $this->_view(null, $row);

			$row = $this->_orderby_x($controller, $row, $this->orderby_s);
			
			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'finance/contract/item/list');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function add($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-3 day'));

		$controller->display($request, 'finance/in/item/add');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function addPost($controller, $request) {
		$this->pretreat($controller);
				
		$customer = $this->_input($request['customer']);
		$transaction = $this->_input($request['transaction']);
		
		$in = $this->_input($request['in_']);
		$emp = $this->_input($request['emp']);
		$engineer = $this->_input($request['engineer']);
		
		$currency = $request['currency'];
		$total = $request['total'];
		$amount = $request['amount'];
		$rate = $request['rate'];
		$rmb = $request['rmb'];
		
		$invoice = $request['invoice'];
		$date = $request['date'];
		
		$name = addslashes($request['name']);
		$type = $request['type'];
		$content = addslashes($request['content']);
				
		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(customer, transaction, `in`, name, type, currency, total, amount, rate, rmb, invoice, date, content, engineer, emp, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, $this->tbl, $customer, $transaction, $in, $name, $type, $currency, $total, $amount, $rate, $rmb, $invoice, $date, $content, $engineer, $emp, $_SESSION['id']);
		debug($sql);
		$db->query($sql);
		
		$request['id_s'] = $db->insert_id();

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/contract/item/edit');
		return true;
	}
	
	function _in($id) {
		require_once(dirname(__FILE__) . '/In.class.php');
		$aa = new In();
		
		return $aa->_view($id);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);
		
		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$in = $this->_input($request['in_']);
		$transaction = $request['transaction'];		
		
		$currency = $request['currency'];
		$total = $request['total'];
		$amount = $request['amount'];
		$rate = $request['rate'];
		$rmb = $request['rmb'];
		
		$invoice = $request['invoice'];
		$date = $request['date'];

		$name = addslashes($request['name']);
		$type = $request['type'];
		$content = addslashes($request['content']);	

		$engineer = $this->_input($request['engineer']);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET `in` = '%s', transaction = '%s', name = '%s', type = '%s', currency = '%s', total = '%s', amount = '%s', rate = '%s', rmb = '%s',";
		$fmt .= "invoice = '%s', date = '%s', content = '%s', engineer = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $in, $transaction, $name, $type, $currency, $total, $amount, $rate, $rmb, $invoice, $date, $content, $engineer, $id);
		debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return false;
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
		
	function copy($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);
		
		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'finance/contract/item/copy');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		// $row['item'] = $this->_out_item($row['id']);
		
		$controller->assign_by_ref('result', $row);
		
		// $controller->assign_by_ref('in', $this->_in($row['in']));
		// $controller->assign_by_ref('tran', $this->_tran($row['transaction']));

		$controller->display($request, 'finance/contract/item/view');
		return true;
	}
	
	function _out_item($id) {
		require_once(dirname(__FILE__) . '/OutItem.class.php');
		$aa = new OutItem();
		
		return $aa->_r_list($id);		
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}
		
		// $row['in_x'] = $this->_in_view($row['in']);
		
		$row['exchange'] = $this->_exchange($row['currency']);
		
		$row = $this->_view_t($row);

		return $row;
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email('307');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '收入明细';

		$cc = array(
			'开票信息'=>array('w' => "DATE_FORMAT(invoice, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),
			'到帐信息'=>array('w' => "DATE_FORMAT(date, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'currency, status'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			return;
		}
		
		$controller->clear_assign('result');
		
		$body = $this->_tj_html($controller, $request, 'finance/in/item/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function tjw($controller, $request) {
		$bb = $this->_list_email('307');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '收入明细（周报）';

		$cc = array(
			'开票信息'=>array('w' => "DATE_FORMAT(invoice, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),
			'到帐信息'=>array('w' => "DATE_FORMAT(date, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),	
			'新增信息'=>array('w' => "DATE_FORMAT(createtime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'currency, status'),
			'更新信息'=>array('w' => "DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		$this->_tj_cc($controller, $cc);
		
		$aa = array(
			'一个星期之内'=>array('w' => "WHERE status = '1' AND invoice >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')"),
			'一个月之内'=>array('w' => "WHERE status = '1' AND invoice >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 MONTH), '%Y-%m-%d')"),
			'三个月之内'=>array('w' => "WHERE status = '1' AND invoice >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')"),
			'半年之内'=>array('w' => "WHERE status = '1' AND invoice >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -6 MONTH), '%Y-%m-%d')"),
			'一年之内'=>array('w' => "WHERE status = '1' AND invoice >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')"),
			'全部'=>array('w' => "")
		);
		
		$this->_tj_bb($controller, $aa);

		$body = $this->_tj_html($controller, $request, 'finance/in/item/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
		
	function _tj2($v) {
		$this->result_s = 10;
		$this->groupby_s = 'currency';
			
		$s = $this->groupby_s;

		if (!empty($v['w'])) {
			$fmt = "SELECT %s AS a, SUM(total*rate) AS c, SUM(total) AS d FROM %s a %s GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $v['w'], $s);
		} else {
			$fmt = "SELECT %s AS a, SUM(total*rate) AS c, SUM(total) AS d FROM %s a WHERE status = '1' GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $s);
		}		
		echo $sql . "\n";

		return $this->_group_tj2($sql);
	}
	
	function _in_view($id) {
		require_once(dirname(__FILE__) . '/Export.class.php');
		$aa = new Export();
		
		return $aa->_view($id);
	}

	function _list($id, $status = 'all') {
		$ret = array();
		
		$db = newdb($this->dsn_r);
		if ($status == 'all') {
			$fmt = "SELECT * FROM %s WHERE `contract` = '%s' AND visible = '1' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id);
		} else {
			$fmt = "SELECT * FROM %s WHERE `contract` = '%s' AND visible = '1' AND status = '%s' ORDER BY id";
			$sql = sprintf($fmt, $this->tbl, $id, $status);
		}
		// debug($sql);
		$result = $db->query($sql);		
		while ($row = $db->fetch_array($result)) {			
			$row = $this->_view($id, $row);			
			$row['ok'] = true; 

			$ret[] = $row;
		}
		
		return $ret;
	}
		
	function _list_amount($id) {
		$a = $this->_list($id);
		
		$ret = 0;
		while (list($k, $v) = each($a)) {
			$ret += $v['total'];
		}
		
		return $ret;
	}
	
	function _list_3($id) {
		
		$cc = array(
			'10'=>array('title'=>'未收信息', 'w' => "customer = $id AND status = 1", 'b'=>'id DESC LIMIT 20'),
			'11'=>array('title'=>'已收信息', 'w' => "customer = $id AND status = 3", 'b'=>'id DESC LIMIT 20'),	
			'12'=>array('title'=>'新增信息', 'w' => "customer = $id AND DATE_FORMAT(createtime, '%Y-%m-%d') > DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')", 'b'=>'currency, status'),
			'13'=>array('title'=>'更新信息', 'w' => "customer = $id AND DATE_FORMAT(modifytime, '%Y-%m-%d') > DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'currency, status'),			
		);
		
		$ret = array();
		while (list($k, $v) = each($cc)) {
			$row = $this->_tj_list($v);
			$row['title'] = $v['title'];
			
			$ret[] = $row;
		}
		
		return $ret;
	}
	
	function _insert($request) {
		
		$id = $request['id'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$supplier = $this->_input($request['supplier']);
		$supplier_x = addslashes($request['supplier_x']);
		
		$currency = $request['currency'];
		$rate = $this->_exchange($currency);
		
		$data = json_decode($request['item'], true);
		
		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(`contract`, name, unit, price, quantity, amount, currency, rate, rmb, mold, content, oper, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		while (list($k, $v) = each($data)) {
			if (empty($v['name']) && empty($v['amount'])) {
				continue;
			}
			
			$name = addslashes($v['name']);			
			if (empty($name)) {
				continue;
			}
			
			// $amount = $v['price'] * $v['quantity'];
			$rmb = $v['amount'] * $rate;
			
			$mold = $this->_input($v['mold_x']);
			$content = addslashes($v['content']);
			
			$sql = sprintf($fmt, $this->tbl, $id, $name, $v['unit'], $v['price'], $v['quantity'], $v['amount'], $currency, $rate, $rmb, $mold, $content, $_SESSION['id']);
			debug($sql);
			$db->query($sql);
		}
		
		$fmt = "UPDATE %s SET office = '%s', emp = '%s', supplier = '%s' WHERE `contract` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $office, $emp, $supplier, $id);
		debug($sql);
		$db->query($sql);
	}
	
	function _update($request) {
		$id = $request['id'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$supplier = $this->_input($request['supplier']);
		$supplier_x = addslashes($request['supplier_x']);
		
		$currency = $request['currency'];
		$rate = $this->_exchange($currency);
		
		$data = json_decode($request['item'], true);
		
		$db = newdb($this->dsn_w);		
		while (list($k, $v) = each($data)) {

			// $amount = $v['price'] * $v['quantity'];
			$rate = $this->_exchange($v['currency']);
			$rmb = $v['amount'] * $rate;
			
			$name = addslashes($v['name']);
			
			$mold = $this->_input($v['mold_x']);
			$content = addslashes($v['content']);
						
			if (array_key_exists("createtime", $v)) {
				if ($v['status'] == 3) {
					continue;
				}
				
				if (!$this->_ok($v['ok'])) {
					// $fmt = "DELETE FROM %s WHERE id = '%s'";
					$fmt = "UPDATE %s SET visible = '2', modifytime = now() WHERE id = '%s'";
					$sql = sprintf($fmt, $this->tbl, $v['id']);
				} else {
					$fmt = "UPDATE %s SET name = '%s', unit = '%s', price = '%s', quantity = '%s', amount = '%s', currency = '%s', rate = '%s', rmb = '%s', mold = '%s', quantity = '%s', content = '%s', modifytime = now() WHERE id = '%s'";
					$sql = sprintf($fmt, $this->tbl, $name, $v['unit'], $v['price'], $v['quantity'], $v['amount'], $currency, $rate, $rmb, $mold, $v['quantity'], $content, $v['id']);
				}			
			} else {
				if (!$this->_ok($v['ok'])) {
					continue;
				}
			
				$fmt = "INSERT INTO %s(`contract`, name, unit, price, quantity, amount, currency, rate, rmb, mold, content, oper, createtime, modifytime)";
				$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
				$sql = sprintf($fmt, $this->tbl, $id, $name, $v['unit'], $v['price'], $v['quantity'], $v['amount'], $currency, $rate, $rmb, $mold, $content, $_SESSION['id']);			
			}
			
			debug($sql);
			$db->query($sql);
		}
		
		$fmt = "UPDATE %s SET office = '%s', emp = '%s', supplier = '%s' WHERE `contract` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $office, $emp, $supplier, $id);
		debug($sql);
		$db->query($sql);
		
		return $ret;
	}
	
	function _contract_status($id, $status) {
		$db = newdb($this->dsn_w);
		
		$fmt = "UPDATE %s SET status = '%s' WHERE `contract` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $status, $id);
		debug($sql);
		$db->query($sql);
	}
		
	function delete($controller, $request) {
		$this->pretreat($controller);

		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
			
			$row = $this->id($this->tbl, $id);
			
			if ($this->_is_delete($row)) {
				$fmt = "DELETE FROM %s WHERE id = '%s'";
				$sql = sprintf($fmt, $this->tbl, $id);
				// debug($sql);
				$db->query($sql);
			}
		}

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}

		if ($row['status'] > 1) {
			return false;
		}

		if ($this->_audit('77')) {
			return true;
		}

		if ($row['oper'] == $_SESSION['id']) {
			return true;
		}

		return false;
	}
	
	function move_id($customer, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE customer = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $customer);
		debug($sql);
		$db->query($sql);
	}
	
	function move($from, $to) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET emp = '%s' WHERE emp = '%s'";
		$sql = sprintf($fmt, $this->tbl, $to, $from);
		debug($sql);
		$db->query($sql);
	}
	
	function group($controller, $request) {
		$this->pretreat_group($controller);

		// $controller->assign('t1', strtotime('-3 month'));
		
		$num = array(
			'1' => '按次数',
			'2' => '按开票金额',
			'3' => '按到帐金额',
			'4' => '按人民币',
		);
		$controller->assign('num_option', $num);

		$controller->display($request, 'finance/in/item/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	function groupby_dd($px) {
		if ($px == '1') {
			return "DATE_FORMAT(date, '%Y-%m-%d %H')";
		}

		if ($px == '2') {
			return "DATE_FORMAT(date, '%Y-%m-%d')";
		}

		if ($px == '3') {
			return "DATE_FORMAT(date, '%Y-%m')";
		}

		return $px;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);

		$num_s = $request['num_s'];
		if (!empty($num_s) && $num_s == '2') {
			$fmt = "SELECT %s AS a, SUM(total) AS c FROM %s a ";
		} else if ($num_s == '3') {
			$fmt = "SELECT %s AS a, SUM(amount) AS c FROM %s a ";
		} else if ($num_s == '4') {
			$fmt = "SELECT %s AS a, SUM(rmb) AS c FROM %s a ";
		} else {
			$fmt = "SELECT %s AS a, COUNT(total) AS c FROM %s a ";
		}
		$sql = sprintf($fmt, $this->s, $this->tbl);

		$where = $this->_where($request);

		$request['sql'] = sprintf("%s %s GROUP BY %s ORDER BY %s %s", $sql, $where, $this->s, $this->orderby, $this->desc);

		$this->_group($controller, $request);

		// $controller->display($request, 'list');
		return true;
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} elseif ($px == 'type') {
			$row['a'] = $this->type[$row['a']];
		} else {

			$row = $this->_name_t($row, $px);
		}

		return $row;
	}
	
	function _delete_in($id) {
		$db = newdb($this->dsn_w);
		$fmt = "DELETE FROM %s WHERE `in` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		// debug($sql);
		$db->query($sql);
	}
		
	function _tj_a($controller, $request) {	
		$s = $this->groupby($controller, $this->groupby_s);
		$df = "DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')";

		$fmt = "SELECT %s as a, SUM(total) as c FROM %s a WHERE invoice >= %s GROUP BY %s ORDER BY c DESC";
		$sql = sprintf($fmt, $s, $this->tbl, $df, $s);
		echo $sql . "\n";

		$this->_group_tj($controller, $sql);

		return $controller->sunxy($request, 'tj_a');
	}
	
	function abc($old, $id) {
		
		$ff = "office, dept, emp, customer, supplier, name, amount, currency, rate, rmb, mold, quantity, weight1, weight2, content, oper, status, visible, createtime, modifytime";
		
		$db = newdb($this->dsn_w);		
		$fmt = "SELECT * FROM %s WHERE export = '%s'";
		$sql = sprintf($fmt, "fy.express_export_item2", $old);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$fmt = "INSERT INTO %s(export, %s) SELECT %s, %s FROM %s WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $ff, $id, $ff, "fy.express_export_item2", $row['id']);
			echo $sql . "\n";
			$db->query($sql);
		}
	}
	
	function z($controller, $request) {
		
		require_once(dirname(__FILE__) . '/In.class.php');
		$aa = new In();
		
		$df = "DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY)";
		$db = newdb($this->dsn_r);
		$fmt = "SELECT `in` FROM %s WHERE status = 3 AND %s GROUP BY `in`";
		// $fmt = "SELECT `in` FROM %s WHERE status = 3 GROUP BY `in`";
		$sql = sprintf($fmt, $this->tbl, $df);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if ($this->_in_item($row['in'])) {
				continue;
			}
			
			$aa->_update_status_3($row['in']);
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function _in_item($id) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE `in` = '%s'";
		$sql = sprintf($fmt, $this->tbl, $id);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if ($row['status'] < 3) {
				return true;
			}
		}
		
		return false;
	}
	
	function n1($controller, $request) {
		$this->payment = $this->_shift($this->payment);
		
		$this->pretreat($controller);

		$from = $this->email;
		
		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE status = '3' AND end < now()";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$to = $row['emp'];
			// $to = "101";
			$row['to'] = Name::emp($to);
	
			$controller->assign_by_ref('result', $row);
			
			$subject = sprintf('[系统通知]收款明细 %s', $row['id']);
			$body = $this->_tj_html($controller, $request, 'finance/in/item/notice_1');	
			
			$to = $this->_emp_email($row['to']);
			// $to = "997264@qq.com";
			$this->mail_html($from, $to, $subject, $body);
			
			if ($row['emp'] <> $row['oper']) {
				$to = $this->_emp_email($row['oper']);
				// $to = "997264@qq.com";
				$this->mail_html($from, $to, $subject, $body);
			}
		}		

		logdate($controller, $request);
		return true;
	}
	
	function b($controller, $request) {
		require_once(dirname(__FILE__) . '/In.class.php');
		$aa = new In();
		
		$t1 = date("Y-m-d", strtotime('-1 month'));
		
		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE modifytime > '%s' GROUP BY `in`";
		$sql = sprintf($fmt, $this->tbl, $t1);
		// echo $sql . "\n";
		$result = $db->query($sql);
		while ($row = $db->fetch_array($result)) {
			if ($this->_b2($aa, $row['in'])) {
				echo "U";
			} else {
				echo ".";
			}
		}
		
		logdate($controller, $request);
		return true;
	}
	
	function _b2($aa, $in) {		
		$db = newdb($this->dsn_w);
		$fmt = "SELECT status, COUNT(*) t FROM %s WHERE `in` = '%s' GROUP BY status ORDER BY t, status";
		$sql = sprintf($fmt, $this->tbl, $in);
		// echo $sql . "\n";
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {			
			return $aa->_u2($in, $row['status']);
		}
		
		return false;
	}
	
	function ajax_code($controller, $request) {

		$data = $this->_ajax_code($request);
		echo json_encode($data);
	}

	function _ajax_code($request) {
		$q = $request['q'];
		$n = $request['maxRows'];
		if (empty($n)) {
			$n = 20;
		}
		
		if (empty($q)) {
			debug("OK" . $q);
			return array();
		}

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s WHERE status = '3' AND id = '%s' ORDER BY id";
		$sql = sprintf($fmt, $this->tbl, $q);
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view($row['id']);
			
			$ret[] = $row;
		}

		return $ret;
	}
}
?>